package com.ogawa.a7517.fragment;

import android.view.View;
import android.widget.ImageView;

import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.ogawa.a7517.DataManager;
import com.ogawa.a7517.R;
import com.ogawa.a7517.adapter.FragmentAdapter;
import com.ogawa.a7517.bean.ProgramBean;

import java.util.ArrayList;
import java.util.List;

public class AutoProgramFragment extends BaseFragment implements View.OnClickListener {
    private ViewPager2 vpAuto;
    private FragmentAdapter adapter;
    private int currentPage;
    private List<Fragment> fragments;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_auto_program;
    }

    @Override
    public void initView(View view) {
        ImageView ivUp = view.findViewById(R.id.iv_up);
        ivUp.setVisibility(View.GONE);
        ivUp.setOnClickListener(this);
        ImageView ivDown = view.findViewById(R.id.iv_down);
        ivDown.setOnClickListener(this);
        vpAuto = view.findViewById(R.id.vp_auto);
        vpAuto.setOrientation(ViewPager2.ORIENTATION_VERTICAL);
        fragments = new ArrayList<>();
        List<ProgramBean> programBeans = DataManager.getInst().getProgramBeans();
        fragments.add(new AutoPageFragment(programBeans.subList(0, 8)));
        fragments.add(new AutoPageFragment(programBeans.subList(8, programBeans.size())));
        adapter = new FragmentAdapter(this, fragments);
        vpAuto.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                currentPage = position;
                ivUp.setVisibility(position == 1 ? View.VISIBLE : View.GONE);
                ivDown.setVisibility(position == 0 ? View.VISIBLE : View.GONE);
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        setTitle(getString(R.string.auto_program));
        vpAuto.setAdapter(adapter);
        vpAuto.setCurrentItem(currentPage, false);
    }

    @Override
    public void onStop() {
        super.onStop();
        vpAuto.setAdapter(null);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_up) {
            vpAuto.setCurrentItem(0);
        } else if (id == R.id.iv_down) {
            vpAuto.setCurrentItem(1);
        }
    }

    @Override
    public void deviceStateChange() {
        super.deviceStateChange();
        for (Fragment fragment : fragments) {
            if (fragment instanceof BaseFragment) {
                ((BaseFragment) fragment).deviceStateChange();
            }
        }
    }
}
